import { settimeNth } from '../../../../global/Func/settimeNth';
import type { empty_void_func } from '../../../../global/Types';
import { css_disnone } from '../../Css';
import { set_static_css } from '../../Css/Func/set_static_css';
import { global_delay_appear } from '../../DataDefine/sourceData';
import { endsTimeAnimation } from '../endsTimeAnimation';
import { remove_class } from '../remove_class';
import { appearEl_operate } from './Classes/cla_appearEl_operate';
import { spacename_appear_dom } from './DataDefine/sourceData';
import type { typ_appear_Direct } from './Types';

/**
 * promise 执行 显示 元素 动画
 * @param elt 目标元素
 * @param direct 显示 方式 默认 "both"
 */
export function appearEl_child_func_promise(
  elt: HTMLElement,
  direct: typ_appear_Direct = 'both'
) {
  let p = new Promise<void>((res) => {
    appearEl_child_func(elt, direct, res);

    /**
     * 逻辑修订
     * 在 元素 显示动画 会 出现 闪现 问题
     */
    remove_class(elt, css_disnone, true);

    settimeNth(global_delay_appear, () => {
      remove_class(elt, css_disnone);
    });
  });

  return p;
}

/**
 * 显示 当前 元素 动画
 * @param elt
 * @param direct
 * @param cb
 */
function appearEl_child_func(
  elt: HTMLElement,
  direct: typ_appear_Direct,
  cb: empty_void_func
) {
  let promise_arr: Promise<void>[] = [];

  /**
   * 循环 查找 当前子元素
   *
   * 并 应用 显示 动画
   */
  let deep_children_func = (elt: HTMLElement) => {
    let uni_child_func = new Promise<void>((res) => {
      appearElFunc(elt, direct, () => {
        res();
      });
    });
    // console.log(elt);
    promise_arr.push(uni_child_func);
    for (const cur_chi_node of elt.children) {
      deep_children_func(cur_chi_node as HTMLElement);
    }
  };

  deep_children_func(elt);

  Promise.all(promise_arr).then(cb);
}

export function appearElFunc(
  elt: HTMLElement,
  direct: typ_appear_Direct,
  cb: empty_void_func,
  duration?: number
) {
  // 创建 对应消失 方向的 生成 集
  let appearObj = new appearEl_operate(elt, direct);

  // 装在元素 id
  let spical_id = `${spacename_appear_dom}_${elt.id}`;

  // 装载 当前 元素的 特定 类 css 信息
  set_static_css(spical_id, appearObj.setstaticCss(duration));

  let { appearEl_anima_cla } = appearObj;

  let delay = endsTimeAnimation(elt, appearEl_anima_cla);

  //   在 元素 结束 动画后 执行 回调函数
  settimeNth(delay, () => {
    if (cb instanceof Function) {
      cb();
    }
  });
}
